<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Painting in Swing</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Painting, drawing, Java, Swing, Graphics, Linux">
<meta name="description" content="This part of the Java Swing tutorial we cover painting in Java Swing.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Painting in Swing</h1>


<p>
Painting is used, when we want to change or enhance an existing widget. 
Or if we are creating a custom widget from scratch.
To do the painting, we use the painting API provided by the Swing toolkit. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>

<p>
The painting is done within the <code>paintComponent()</code> method. 
In the painting process, we use the 
<code>Graphics2D</code> object. 
</p>


<h2>2D Vector Graphics</h2>

<p>
There are two different computer graphics. Vector and raster graphics. Raster 
graphics represents images as a collection of pixels. Vector graphics is the 
use of geometrical primitives such as points, lines, curves or polygons to 
represent images. These primitives are created using mathematical equations.
</p>

<p>
Both types of computer graphics have advantages and disadvantages. The advantages 
of vector graphics over raster are:
</p>

<ul>
 <li>smaller size</li>
 <li>ability to zoom indefinitely</li>
 <li>moving, scaling, filling or rotating does not degrade the quality of an image</li>
</ul>

<h3>Types of primitives</h3>

<ul>
  <li>points</li>
  <li>lines</li>
  <li>polylines</li>
  <li>polygons</li>
  <li>circles</li>
  <li>ellipses</li>
  <li>Splines</li>
</ul>


<h2>Points</h2>

<p>
The most simple graphics primitive is point. It is a single dot on the window. 
There is no method to draw a point in Swing. To draw a point, 
we use the <code>drawLine()</code> method. We use one point twice. 
</p>

<pre class="code">
package zetcode;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


class DrawPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(Color.blue);

        for (int i = 0; i &lt;= 1000; i++) {
            Dimension size = getSize();
            Insets insets = getInsets();

            int w = size.width - insets.left - insets.right;
            int h = size.height - insets.top - insets.bottom;

            Random r = new Random();
            int x = Math.abs(r.nextInt()) % w;
            int y = Math.abs(r.nextInt()) % h;
            g2d.drawLine(x, y, x, y);
        }

    }
}

public class PointsExample extends JFrame {

    public PointsExample() {
        initUI();
    }

    public final void initUI() {

        DrawPanel dpnl = new DrawPanel();
        add(dpnl);

        setSize(250, 200);
        setTitle("Points");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                PointsExample ex = new PointsExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
One point is difficult to observe. Why not paint 1000 of them. 
In our example, we do so. We draw 1000 blue points on the 
panel. 
</p>

<pre class="explanation">
class DrawPanel extends JPanel {
</pre>

<p>
We are drawing on a custom drawing panel, which is a 
<code>JPanel</code> component. The drawing panel will later be
added to a <code>JFrame</code> component. 
</p>

<pre class="explanation">
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
</pre>

<p>
The painting is performed inside the <code>paintComponent()</code>
method. 
</p>

<pre class="explanation">
Graphics2D g2d = (Graphics2D) g;
</pre>

<p>
Painting in Swing is done on the <code>Graphics2D</code> object.
</p>

<pre class="explanation">
g2d.setColor(Color.blue);
</pre>

<p>
We will paint our points in blue color.
</p>

<pre class="explanation">
Dimension size = getSize();
Insets insets = getInsets();
</pre>

<p>
The size of the window includes borders and titlebar. We don't paint there.
</p>


<pre class="explanation">
int w =  size.width - insets.left - insets.right;
int h =  size.height - insets.top - insets.bottom;
</pre>

<p>
Here we calculate the area, where we will effectively paint our points. 
</p>

<pre class="explanation">
Random r = new Random();
int x = Math.abs(r.nextInt()) % w;
int y = Math.abs(r.nextInt()) % h;
</pre>

<p>
We get a random number in range of the size of area, that we computed above.
</p>


<pre class="explanation">
g2d.drawLine(x, y, x, y);
</pre>

<p>
Here we draw the point. As I already said, we use a <code>drawLine()</code> 
method. We specify the same point twice.
</p>

<img src="/img/gui/javaswing/points.png" alt="Points">
<div class="figure">Figure: Points</div>


<h2>Lines</h2>

<p>
A line is a simple graphics primitive. It is drawn using two points. 
</p>


<pre class="code">
package zetcode;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;



class DrawPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

            float[] dash1 = { 2f, 0f, 2f };
            float[] dash2 = { 1f, 1f, 1f };
            float[] dash3 = { 4f, 0f, 2f };
            float[] dash4 = { 4f, 4f, 1f };

            g2d.drawLine(20, 40, 250, 40);

            BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f );

            BasicStroke bs2 = new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_ROUND, 1.0f, dash2, 2f );

            BasicStroke bs3 = new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_ROUND, 1.0f, dash3, 2f );

            BasicStroke bs4 = new BasicStroke(1, BasicStroke.CAP_BUTT,
                BasicStroke.JOIN_ROUND, 1.0f, dash4, 2f );

            g2d.setStroke(bs1);
            g2d.drawLine(20, 80, 250, 80);

            g2d.setStroke(bs2);
            g2d.drawLine(20, 120, 250, 120);

            g2d.setStroke(bs3);
            g2d.drawLine(20, 160, 250, 160);

            g2d.setStroke(bs4);
            g2d.drawLine(20, 200, 250, 200);

    }
}

public class LinesExample extends JFrame {

    public LinesExample() {
        initUI();
    }

    public final void initUI() {

        DrawPanel dpnl = new DrawPanel();
        add(dpnl);

        setSize(280, 270);
        setTitle("Lines");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                LinesExample ex = new LinesExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In the example, we draw five lines. The first line is drawn using the 
default values. Other will have a different <b>stroke</b>. The stroke is created using
the <code>BasicStroke</code> class. It defines a basic set 
of rendering attributes for the outlines of graphics primitives. 
</p>

<pre class="explanation">
float[] dash1 = { 2f, 0f, 2f };
</pre>

<p>
Here we create a dash, that we use in the stroke object.
</p>

<pre class="explanation">
BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT, 
    BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f )
</pre>

<p>
This code creates a stroke. The stroke defines the line width, end caps, 
line joins, miter limit, dash and the dash phase.
</p>

<img src="/img/gui/javaswing/lines.png" alt="Lines">
<div class="figure">Figure: Lines</div>



<h2>Rectangles</h2>

<p>
To draw rectangles, we use the <code>drawRect()</code> method. 
To fill rectangles with the current color, we
use the <code>fillRect()</code> method.
</p>

<pre class="code">
package zetcode;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


class DrawPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(new Color(212, 212, 212));
            g2d.drawRect(10, 15, 90, 60);
            g2d.drawRect(130, 15, 90, 60);
            g2d.drawRect(250, 15, 90, 60);
            g2d.drawRect(10, 105, 90, 60);
            g2d.drawRect(130, 105, 90, 60);
            g2d.drawRect(250, 105, 90, 60);
            g2d.drawRect(10, 195, 90, 60);
            g2d.drawRect(130, 195, 90, 60);
            g2d.drawRect(250, 195, 90, 60);

            g2d.setColor(new Color(125, 167, 116));
            g2d.fillRect(10, 15, 90, 60);

            g2d.setColor(new Color(42, 179, 231));
            g2d.fillRect(130, 15, 90, 60);

            g2d.setColor(new Color(70, 67, 123));
            g2d.fillRect(250, 15, 90, 60);

            g2d.setColor(new Color(130, 100, 84));
            g2d.fillRect(10, 105, 90, 60);

            g2d.setColor(new Color(252, 211, 61));
            g2d.fillRect(130, 105, 90, 60);

            g2d.setColor(new Color(241, 98, 69));
            g2d.fillRect(250, 105, 90, 60);

            g2d.setColor(new Color(217, 146, 54));
            g2d.fillRect(10, 195, 90, 60);

            g2d.setColor(new Color(63, 121, 186));
            g2d.fillRect(130, 195, 90, 60);

            g2d.setColor(new Color(31, 21, 1));
            g2d.fillRect(250, 195, 90, 60);
    }
}

public class RectanglesExample extends JFrame {

    public RectanglesExample() {
        initUI();
    }

    public final void initUI() {

        DrawPanel dpnl = new DrawPanel();
        add(dpnl);

        setSize(360, 300);
        setTitle("Rectangles");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                RectanglesExample ex = new RectanglesExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In the example we draw nine colored rectangles. 
</p>

<pre class="explanation">
g2d.setColor(new Color(212, 212, 212));
g2d.drawRect(10, 15, 90, 60);
...
</pre>

<p>
We set the color of the outline of the rectangle to a soft 
gray color, so that it does not interfere with 
the fill color. To draw the outline of the rectangle, 
we use the <code>drawRect()</code> method.
The first two parameters are the x and y values. 
The third and fourth are width and height. 
</p>

<pre class="explanation">
g2d.fillRect(10, 15, 90, 60);
</pre>

<p>
To fill the rectangle with a color, we use the <code>fillRect()</code> method.
</p>

<img src="/img/gui/javaswing/rectangles.png" alt="Rectangles">
<div class="figure">Figure: Rectangles</div>


<h2>Textures</h2>

<p>
A <b>texture</b> is a bitmap image applied to the surface in computer graphics. 
Besides colors and gradients, we can fill 
our graphics shapes with textures.
</p>


<pre class="code">
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;


public class Textures extends JPanel {


    public void paintComponent(Graphics g) {
            super.paintComponent(g); 

            Graphics2D g2d = (Graphics2D) g;

            g2d.setColor(new Color(212, 212, 212));
            g2d.drawRect(10, 15, 90, 60);
            g2d.drawRect(130, 15, 90, 60);
            g2d.drawRect(250, 15, 90, 60);
            g2d.drawRect(10, 105, 90, 60);
            g2d.drawRect(130, 105, 90, 60);
            g2d.drawRect(250, 105, 90, 60);

            BufferedImage bimage1 = null;
            BufferedImage bimage2 = null;
            BufferedImage bimage3 = null;
            BufferedImage bimage4 = null;
            BufferedImage bimage5 = null;
            BufferedImage bimage6 = null;

            URL url1 = ClassLoader.getSystemResource("texture1.png");
            URL url2 = ClassLoader.getSystemResource("texture2.png");
            URL url3 = ClassLoader.getSystemResource("texture3.png");
            URL url4 = ClassLoader.getSystemResource("texture4.png");
            URL url5 = ClassLoader.getSystemResource("texture5.png");
            URL url6 = ClassLoader.getSystemResource("texture6.png");

            try {
                bimage1 = ImageIO.read(url1);
                bimage2 = ImageIO.read(url2);
                bimage3 = ImageIO.read(url3);
                bimage4 = ImageIO.read(url4);
                bimage5 = ImageIO.read(url5);
                bimage6 = ImageIO.read(url6);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }

            Rectangle rect1 = new Rectangle(0, 0,
                bimage1.getWidth(), bimage1.getHeight());

            Rectangle rect2 = new Rectangle(0, 0,
                bimage2.getWidth(), bimage2.getHeight());

            Rectangle rect3 = new Rectangle(0, 0,
                bimage3.getWidth(), bimage3.getHeight());

            Rectangle rect4 = new Rectangle(0, 0,
                bimage4.getWidth(), bimage4.getHeight());

            Rectangle rect5 = new Rectangle(0, 0,
                bimage5.getWidth(), bimage5.getHeight());

            Rectangle rect6 = new Rectangle(0, 0,
                bimage6.getWidth(), bimage6.getHeight());

            TexturePaint texture1 = new TexturePaint(bimage1, rect1);
            TexturePaint texture2 = new TexturePaint(bimage2, rect2);
            TexturePaint texture3 = new TexturePaint(bimage3, rect3);
            TexturePaint texture4 = new TexturePaint(bimage4, rect4);
            TexturePaint texture5 = new TexturePaint(bimage5, rect5);
            TexturePaint texture6 = new TexturePaint(bimage6, rect6);

            g2d.setPaint(texture1);
            g2d.fillRect(10, 15, 90, 60);

            g2d.setPaint(texture2);
            g2d.fillRect(130, 15, 90, 60);

            g2d.setPaint(texture3);
            g2d.fillRect(250, 15, 90, 60);

            g2d.setPaint(texture4);
            g2d.fillRect(10, 105, 90, 60);

            g2d.setPaint(texture5);
            g2d.fillRect(130, 105, 90, 60);

            g2d.setPaint(texture6);
            g2d.fillRect(250, 105, 90, 60);
    }

    public static void main(String[] args) {

        Textures rects = new Textures();
        JFrame frame = new JFrame("Textures");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(rects);
        frame.setSize(360, 210);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }
}
</pre>


<p>
In our example, we will draw six rectangles filled with different textures. 
To work with textures, Java Swing has a <code>TexturePaint</code> class.
</p>

<pre class="explanation">
BufferedImage bimage1 = null;
...
URL url1 = ClassLoader.getSystemResource("texture1.png");
...
bimage1 = ImageIO.read(url1);
</pre>

<p>
We read an image into the memory.
</p>

<pre class="explanation">
Rectangle rect1 = new Rectangle(0, 0,
    bimage1.getWidth(), bimage1.getHeight());
</pre>

<p>
We get the size of the texture image.
</p>

<pre class="explanation">
TexturePaint texture1 = new TexturePaint(bimage1, rect1);
</pre>

<p>
Here we create a <code>TexturePaint</code> object. The parameters are a 
buffered image and a rectangle of the image. The rectangle is used to anchor and 
replicate the image. The images are tiled. 
</p>

<pre class="explanation">
g2d.setPaint(texture1);
g2d.fillRect(10, 15, 90, 60);
</pre>

<p>
Here we apply the texture and fill the rectangle with it.
</p>

<img src="/img/gui/javaswing/textures.jpg" alt="Textures">
<div class="figure">Figure: Textures</div>


<h2>Gradients</h2>

<p>
In computer graphics, gradient is a smooth blending of shades from light to 
dark or from one color to another. In 2D drawing programs and paint programs, 
gradients are used to create colorful backgrounds and special effects as well 
as to simulate lights and shadows. (answers.com)
</p>


<pre class="code">
package zetcode;

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;
        GradientPaint gp1 = new GradientPaint(5, 5,
                Color.red, 20, 20, Color.black, true);

        g2d.setPaint(gp1);
        g2d.fillRect(20, 20, 300, 40);

        GradientPaint gp2 = new GradientPaint(5, 25,
                Color.yellow, 20, 2, Color.black, true);

        g2d.setPaint(gp2);
        g2d.fillRect(20, 80, 300, 40);

        GradientPaint gp3 = new GradientPaint(5, 25,
                Color.green, 2, 2, Color.black, true);

        g2d.setPaint(gp3);
        g2d.fillRect(20, 140, 300, 40);

        GradientPaint gp4 = new GradientPaint(25, 25,
                Color.blue, 15, 25, Color.black, true);

        g2d.setPaint(gp4);
        g2d.fillRect(20, 200, 300, 40);

        GradientPaint gp5 = new GradientPaint(0, 0,
                Color.orange, 0, 20, Color.black, true);

        g2d.setPaint(gp5);
        g2d.fillRect(20, 260, 300, 40);
    }
}

public class GradientsExample extends JFrame {

    public GradientsExample() {
        initUI();
    }

    public final void initUI() {

        DrawPanel dpnl = new DrawPanel();
        add(dpnl);

        setSize(350, 350);
        setTitle("Gradients");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                GradientsExample ex = new GradientsExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
Our code example presents five rectangles with gradients. 
</p>

<pre class="explanation">
GradientPaint gp4 = new GradientPaint(25, 25, 
    Color.blue, 15, 25, Color.black, true);
</pre>

<p>
To work with gradients, we use Java Swing's <code>GradientPaint</code> class.
By manipulating the color values and the starting end ending points, we can get 
interesting results.
</p>

<pre class="explanation">
g2d.setPaint(gp5);
</pre>

<p>
The gradient is activated calling the <code>setPaint()</code> method.
</p>


<img src="/img/gui/javaswing/gradients.png" alt="Gradients">
<div class="figure">Figure: Gradients</div>


<h2>Drawing text</h2>


<p>
Drawing is done with the <code>drawString()</code> method. We specify the string we want
to draw and the position of the text on the window area.
</p>

<pre class="code">
import java.awt.Font;
package zetcode;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        rh.put(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);

        g2d.setRenderingHints(rh);

        Font font = new Font("URW Chancery L", Font.BOLD, 21);
        g2d.setFont(font);

        g2d.drawString("Not marble, nor the gilded monuments", 20, 30);
        g2d.drawString("Of princes, shall outlive this powerful rhyme;", 20, 60);
        g2d.drawString("But you shall shine more bright in these contents",
                20, 90);
        g2d.drawString("Than unswept stone, besmear'd with sluttish time.",
                20, 120);
        g2d.drawString("When wasteful war shall statues overturn,", 20, 150);
        g2d.drawString("And broils root out the work of masonry,", 20, 180);
        g2d.drawString("Nor Mars his sword, nor war's quick "
                + "fire shall burn", 20, 210);
        g2d.drawString("The living record of your memory.", 20, 240);
        g2d.drawString("'Gainst death, and all oblivious enmity", 20, 270);
        g2d.drawString("Shall you pace forth; your praise shall still "
                + "find room", 20, 300);
        g2d.drawString("Even in the eyes of all posterity", 20, 330);
        g2d.drawString("That wear this world out to the ending doom.", 20, 360);
        g2d.drawString("So, till the judgment that yourself arise,", 20, 390);
        g2d.drawString("You live in this, and dwell in lovers' eyes.", 20, 420);
    }
}

public class TextExample extends JFrame {

    public TextExample() {
        initUI();
    }

    public final void initUI() {

        DrawPanel dpnl = new DrawPanel();
        add(dpnl);

        setSize(500, 470);
        setTitle("Sonnet55");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TextExample ex = new TextExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
In our example, we draw a sonnet on the panel component. 
</p>

<pre class="explanation">
RenderingHints rh = new RenderingHints(
    RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);

rh.put(RenderingHints.KEY_RENDERING, 
    RenderingHints.VALUE_RENDER_QUALITY);

g2d.setRenderingHints(rh);
</pre>

<p>
This code is to make our text look better. We apply a technique 
called <b>antialiasing</b>.
</p>

<pre class="explanation">
Font font = new Font("URW Chancery L", Font.BOLD, 21);
g2d.setFont(font);
</pre>

<p>
We choose a nice font for our text. 
</p>

<pre class="explanation">
g2d.drawString("Not marble, nor the gilded monuments", 20, 30);
</pre>

<p>
This is the code, that draws the text.
</p>



<h2>Images</h2>

<p>
On of the most important capabililies of a toolkit is the ability to display images.
An image is an array of pixels. Each pixel represents a color at a given position.
We can use components like <code>JLabel</code> to display an image, or we 
can draw it using the <code>Java 2D API</code>.
</p>


<pre class="code">
package zetcode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawPanel extends JPanel {

    Image img;

    public DrawPanel(Image img) {
        this.img = img;
        Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null));
        setPreferredSize(dm);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

        g2d.drawImage(this.img, 0, 0, null);
    }
}

public class ImageExample extends JFrame {

    public ImageExample() {
        initUI();
    }

    public final void initUI() {

        Image img = new ImageIcon("slanec.png").getImage();

        DrawPanel dpnl = new DrawPanel(img);
        add(dpnl);

        setTitle("Image");
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                ImageExample ex = new ImageExample();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
This example will draw an image on the panel. The image will fit the
<code>JFrame</code> window. 
</p>

<pre class="explanation">
public DrawPanel(Image img) {
    this.img = img;
    Dimension dm = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(dm);
}
</pre>

<p>
We determine the image dimensions and set the preffered size of
the panel component. This will together with the <code>pack()</code>
method display the image to fit exactly the window. 
</p>

<pre class="explanation">
g2d.drawImage(this.img, 0, 0, null);
</pre>

<p>
The image is drawn using the <code>drawImage()</code> method.
</p>

<pre class="explanation">
Image img = new ImageIcon("slanec.png").getImage();
</pre>

<p>
We load the image using the <code>ImageIcon</code> class. This
class simplyfies the work with the images in Java Swing. 
</p>


<p>
In this chapter, we did some painting. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 12, 2007  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

